package config

import (
	"io/ioutil"
	"time"

	"gopkg.in/yaml.v3"
)

var AppConfig *Config

// Config 应用配置结构体
type Config struct {
	Server   ServerConfig   `yaml:"server"`
	Database DatabaseConfig `yaml:"database"`
	Storage  StorageConfig  `yaml:"storage"`
	JWT      JWTConfig      `yaml:"jwt"`
	Log      LogConfig      `yaml:"log"`
	Security SecurityConfig `yaml:"security"`
	Secret   string         `json:"secret"`
}

// ServerConfig 服务器配置
type ServerConfig struct {
	Port         int           `yaml:"port"`
	ReadTimeout  time.Duration `yaml:"read_timeout"`
	WriteTimeout time.Duration `yaml:"write_timeout"`
	IdleTimeout  time.Duration `yaml:"idle_timeout"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Driver          string        `yaml:"driver"`
	DSN             string        `yaml:"dsn"`
	MaxOpenConns    int           `yaml:"max_open_conns"`
	MaxIdleConns    int           `yaml:"max_idle_conns"`
	ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime"`
}

// StorageConfig 文件存储配置
type StorageConfig struct {
	RootPath          string   `yaml:"root_path"`
	MaxFileSize       int64    `yaml:"max_file_size"`
	AllowedExtensions []string `yaml:"allowed_extensions"`
}

// JWTConfig JWT配置
type JWTConfig struct {
	Secret       string        `yaml:"secret"`
	ExpiresHours time.Duration `yaml:"expires_hours"`
}

// LogConfig 日志配置
type LogConfig struct {
	Level     string `yaml:"level"`
	Output    string `yaml:"output"`
	FilePath  string `yaml:"file_path"`
	MaxSize   int    `yaml:"max_size"`
	MaxBackup int    `yaml:"max_backup"`
	MaxAge    int    `yaml:"max_age"`
}

// SecurityConfig 安全配置
type SecurityConfig struct {
	AllowedOrigins  []string      `yaml:"allowed_origins"`
	CorsEnabled     bool          `yaml:"cors_enabled"`
	TokenExpiryDays time.Duration `yaml:"token_expiry_days"`
}

// Load 从文件加载配置
func Load(filePath string) (*Config, error) {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, err
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		return nil, err
	}

	return &config, nil
}
